package com.qian.ddj.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qian.api.ddj.model.*;
import com.qian.api.ddj.service.IAliCode2Service;
import com.qian.api.ddj.service.IAliCodeService;
import com.qian.api.ddj.service.IBusinessService;
import com.qian.api.ddj.service.IOrderService;
import com.qian.ddj.pay.util.shyqUtil.PayUtils;
import com.yaowk.api.common.PageReq;
import com.yaowk.web.common.adapter.ResponseString;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

@Controller
@ResponseString
@RequestMapping("/notify")
public class NotifyController {

    private final Logger logger = LoggerFactory.getLogger(NotifyController.class);

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IAliCodeService aliCodeService;
    @Autowired
    private IAliCode2Service aliCode2Service;

    @RequestMapping("/notifyToUser/{id}")
    public void notify2User(@PathVariable Integer id) {
        Order order = new Order();
        order.setId(id);
        orderService.notifyToUser(order);
    }

    @RequestMapping("/test")
    public void test(HttpServletRequest request) {
        System.out.println(request.getParameter("sign"));
    }

    @RequestMapping("/selfZFBNotify")
    public String selfZFBNotify(HttpServletRequest request) {
        if ("9902312".equalsIgnoreCase(request.getParameter("key")) && "151261552310206".equalsIgnoreCase(request.getParameter("appid"))) {
            String remark = request.getParameter("PayMore");
            BigDecimal amount = new BigDecimal(request.getParameter("PayJe"));
            String payType = request.getParameter("payType");
            AliCode aliCode = null;
            AliCode2 aliCode2 = null;
            Integer businessId = null;
            if (StringUtils.isNotBlank(remark)) {
                businessId = new Integer(remark.split("-")[0]);
                aliCode = new AliCode();
                aliCode.setBusinessId(businessId);
                aliCode.setAmount(amount);
                aliCode.setRemark(remark);
//                aliCode.setPayType(new Byte(payType));
                aliCode.setStatus(StatusDict.WAIT_PAY);
                aliCode = aliCodeService.findOne(aliCode);
            } else {
                remark = amount.toString();
                aliCode2 = new AliCode2();
                aliCode2.setRemark(remark);
//                aliCode2.setPayType(new Byte(payType));
                aliCode2.setStatus(StatusDict.WAIT_PAY);
                aliCode2 = aliCode2Service.findOne(aliCode2);
            }
            if (!ObjectUtils.isEmpty(aliCode) || !ObjectUtils.isEmpty(aliCode2)) {
                Order order = new Order();
                if (!ObjectUtils.isEmpty(businessId)) {
                    order.setBusinessId(businessId);
                }
                order.setRealAmount(amount);
                order.setRemark(remark);
                order.setStatus(StatusDict.WAIT_PAY);
                PageReq pageReq = new PageReq();
                pageReq.setPageSize(1);
                pageReq.setPageNumber(1);
                order = orderService.findAll(order, pageReq).getList().get(0);
                if (!ObjectUtils.isEmpty(order)) {
                    order.setUpOrderNo(request.getParameter("PayNO"));
                    orderService.orderFinish(order);
                    if (!ObjectUtils.isEmpty(aliCode)) {
                        aliCode.setStatus(StatusDict.NORMAL);
                        aliCodeService.save(aliCode);
                    } else if (!ObjectUtils.isEmpty(aliCode2)) {
                        aliCode2.setStatus(StatusDict.NORMAL);
                        aliCode2Service.save(aliCode2);
                    }
                    try {
                        String rec = orderService.notifyToUser(order);
                        logger.info("{} receive {}", order.getOutOrderNo(), rec);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info(e.getMessage());
                    }
                    return "Success";
                }
            }
        }
        return "Fail";
    }

    @RequestMapping("/jdfNotify")
    public String jdfNotify(HttpServletRequest request) {
        Map<String, String> map = new TreeMap<>();
        map.put("version", request.getParameter("version"));
        map.put("merchantId", request.getParameter("merchantId"));//商户
        map.put("orderNo", request.getParameter("orderNo"));//订单号
        map.put("tradeDate", request.getParameter("tradeDate"));//交易日
        map.put("tradeTime", request.getParameter("tradeTime"));//交易时间
        map.put("amount", request.getParameter("amount"));//金额
        map.put("attach", request.getParameter("attach"));
        map.put("resultCode", request.getParameter("resultCode"));//状态

        if (org.springframework.util.StringUtils.isEmpty(map.get("attach"))) {
            map.remove("attach");
        }
        System.out.println(map);
        String sign = request.getParameter("sign");//签名
        System.out.println(sign);
        Order order = orderService.findByOrderNo(map.get("orderNo"));
        System.out.println("===========");
        System.out.println(order);
        System.out.println(order.getBusinessId());
        Business business = businessService.findById(order.getBusinessId());
        String sign1 = com.qian.ddj.pay.util.SignUtils.createSign(map, business.getSecretKey()).toLowerCase();
        System.out.println(sign1);
        System.out.println(sign1.equals(sign));
        if (sign1.equals(sign)) {
            if ("0".equals(map.get("resultCode"))) {
                try {
                    orderService.orderFinish(order);
                    String receive = orderService.notifyToUser(order);
                    return "success";
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                }
            }
        }
        return "";
    }

    @RequestMapping("/YLNotify")
    public String YLNotify(@RequestBody String result) {
        System.out.println("SJFHSJ==========" + result);
        JSONObject jb = JSONObject.parseObject(result);
        Map<String, String> map = new LinkedHashMap<>();
        map.put("goods_name", jb.getString("goods_name"));//商品名称
        map.put("out_trade_no", jb.getString("out_trade_no"));//商户单号
        map.put("total_amount", jb.getString("total_amount"));//交易金额(单位:元)
        map.put("trade_no", jb.getString("trade_no"));
        map.put("version", jb.getString("version"));//版本
        map.put("sign_type", jb.getString("sign_type"));
        map.put("remarks", jb.getString("remarks"));//交易备注
        map.put("status", jb.getString("status"));//状态
        map.put("pay_time", jb.getString("pay_time"));//
        String Sign = jb.getString("sign");
        //map.put("sign",jb.getString("sign"));
        map.remove("sign");
        map.remove("sign_type");
        System.out.println(map);
        System.out.println("====JMSJ====" + map.toString());
        System.out.println(Sign);
        Order order = orderService.findByOrderNo(map.get("out_trade_no"));
        System.out.println(order);

        Business business = businessService.findById(order.getBusinessId());
        System.out.println("BUSINESS:");
        System.out.println(business.toString());
        String sign1 = com.qian.ddj.pay.util.YLUtils.ApiUtils.getSign(map, business.getSecretKey().toUpperCase());//查询秘钥

        System.out.println(sign1);
        System.out.println(sign1.equals(Sign));
        if (sign1.equals(Sign)) {
            if ("1000".equals(map.get("status"))) {
                orderService.orderFinish(order);
                String receice = orderService.notifyToUser(order);
                if ("sucess".equals(receice))
                    return "sucess";
            }

        }

        return "";
    }

    @RequestMapping("/shyqNotify")
    public String shyqNotify(@RequestBody String recive){
        try {
           recive =URLDecoder.decode(recive,"utf-8").replaceAll("msg=","");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int begin = recive.indexOf("{\"");
        int end = recive.indexOf("\"}|");
        String jsonString = recive.substring(begin,end)+"\"}";
        JSONObject jb = JSON.parseObject(jsonString);
        System.out.println(jb);
       String orderNo = jb.getString("traceNO");
       Order order = orderService.findByOrderNo(orderNo);
       Business business = businessService.findById(order.getBusinessId());
//        String key = "aqww960nwg6gcs7h9m0woz65hrgzj5ph64knk3mitxp0q3bd6vn0u5afetnnxkjyo0ziwkcz";
        if (PayUtils.checkSign(recive,business.getSecretKey())){
            if (recive.indexOf("000|{\"") != -1){
                orderService.orderFinish(order);
                String receice = orderService.notifyToUser(order);
                if ("sucess".equals(receice))
                System.out.println("支付成功！");
                    return "Y";
            }
        }
        return "";
    }

}




